import Vue from 'vue'
import VueRouter from 'vue-router'

// import Login from '@/views/login'
// import Layout from '@/views/layout'
// import Welcome from '@/views/welcome'
// import Article from '@/views/article'
// import Image from '@/views/image'
// import Publish from '@/views/publish'
// import Comment from '@/views/comment'
// import Fans from '@/views/fans'
// import Setting from '@/views/setting'
// import NotFound from '@/views/404.vue'

//路由懒加载
const Login = () => import('@/views/login')
const Layout = () => import('@/views/layout')
const Welcome = () => import('@/views/welcome')
const Article = () => import('@/views/article')
const Image = () => import('@/views/image')
const Publish = () => import('@/views/publish')
const Comment = () => import('@/views/comment')
const Fans = () => import('@/views/fans')
const Setting = () => import('@/views/setting')
const NotFound = () => import('@/views/404')

import auth from '@/utils/auth'

Vue.use(VueRouter)

const routes = [
    { path: '/login', component: Login },
    {
      path: '/',
      component: Layout,
      children: [
          { path: '/', component: Welcome },
          { path: '/article', component: Article },
          { path: '/image', component: Image },
          { path: '/publish', component: Publish },
          { path: '/comment', component: Comment },
          { path: '/fans', component: Fans },
          { path: '/setting', component: Setting }
      ]
    },
    { path: '*', component: NotFound }
]

const router = new VueRouter({ routes })

router.beforeEach((to, from, next) => {
    // 解构得到获取用信息的函数
    const { getUser } = auth
    // 除去登录外，其他页面需要判断token是否存在，如果不存储拦截到登录
    if (to.path !== '/login' && !getUser().token) return next('/login')
    // 其他情况一律放行
    next()
})

export default router